# -*- coding: UTF-8 -*-

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import time, urllib
from datetime import date
from django.utils import simplejson

class MainPage(webapp.RequestHandler):
    apikey = 'KLUCZ_API_DOSTEPNY_TUTAJ_http://spinacz.pl/api'
    apiurl = 'http://spinacz.pl/feeds/add.json?HASH=%s&%s'
    
    def buildMessage(self):
        dzien = date.fromtimestamp(time.time()).weekday()
        msg = "Czy to piątek? ";
        if dzien < 4:
            ile = 4 - dzien;
            msg+= "NIE!\nDo piątku ";
            if ile == 1:
                msg+="pozostał dzień :)";
            else:
                msg+="pozostały "+str(ile)+" dni...";
        elif dzien == 4:
            msg = "TAK!!! Huurra! W końcu piątek ;)";
        elif dzien > 5:
            msg = "Może nie piątek ale weekendzik - to się liczy ;)";
        msg+=" #czytopiatek";
        return msg
    
    def sendMessage(self):
        url = self.apiurl % (self.apikey, urllib.urlencode({'content':self.buildMessage()}))
        
        f = urllib.urlopen(url)
        try:
            status = simplejson.loads(f.read())
            return status['status']
        except:
            pass
        return 'ERROR'
    
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(self.sendMessage())
application = webapp.WSGIApplication([('/', MainPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
